/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
        '"}'
    )
}
/**
 * @param {} value
 * @param {string} key
 * @param {array} arr
 */
export function getPathByKey(value, key, arr) {
    const temppath = []
    try {
        // eslint-disable-next-line no-inner-declarations
        function getNodePath(node) {
            temppath.push(node)
                // 找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
                // eslint-disable-next-line no-throw-literal
                throw ('GOT IT!')
            }
            if (node.children && node.children.length > 0) {
                for (var i = 0; i < node.children.length; i++) {
                    getNodePath(node.children[i])
                }
                // 当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
                temppath.pop()
            } else {
                // 找到叶子节点时，删除路径当中的该叶子节点
                temppath.pop()
            }
        }
        for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i])
        }
    } catch (e) {
        return temppath[0]
    }
}

// 获取时间段内所有日期
export function getDateArrByRange(startDate, endDate, cFormat) {
    const format = cFormat || '{y}-{m}-{d}'
    startDate = parseTime(startDate, format)
    endDate = parseTime(endDate, format)
    const startArr = startDate.split('-')
    const endArr = endDate.split('-')
    const arrTime = []
    const _startArr = new Date()
    const _endArr = new Date()
    _startArr.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
    _endArr.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
    const unixDb = _startArr.getTime()
    const unixDe = _endArr.getTime()
    for (let timestamp = unixDb; timestamp <= unixDe;) {
        arrTime.push(parseTime(timestamp, format))
        timestamp = timestamp + 24 * 60 * 60 * 1000
    }
    return arrTime
}

 export function getURLParam(strParamName, url) {

      var strReturn = "";
      var strHref = url;
    
      if (strHref.indexOf("?") > -1) {
          var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
          var aQueryString = strQueryString.split("&");
          for (var iParam = 0; iParam < aQueryString.length; iParam++) {
              if (aQueryString[iParam].indexOf(strParamName+ "=") > -1) {
                  var aParam = aQueryString[iParam].split("=");
                  strReturn = aParam[1];
                  break;
              }
          }
      }
      return strReturn;
}